package com.example.mvvmkotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.example.mvvmkotlin.databinding.ActivityMainBinding
import com.google.android.material.appbar.AppBarLayout.Behavior
import com.google.android.material.tabs.TabLayoutMediator

class MainActivity : AppCompatActivity() {
    lateinit var binding:ActivityMainBinding
    private val titleList = arrayListOf<String>("第一个", "第二个", "第三个", "第四个")
    private lateinit var fragmentList : MutableList<Fragment>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
    }

    private fun initView() {
        fragmentList = ArrayList<Fragment>()
        fragmentList.add(TestFragment.newInstance())
        fragmentList.add(TestFragment.newInstance())
        fragmentList.add(TestFragment.newInstance())
        fragmentList.add(TestFragment.newInstance())
        val fragmentAdapter = FragmentAdapter(this)
        binding.vp2Content.adapter = fragmentAdapter
        TabLayoutMediator(binding.tlTitle, binding.vp2Content) {tab, position ->
            tab.text = titleList[position]
        }.attach()
        binding.vp2Content.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
            }
        })

    }

    private inner class FragmentAdapter(fa:FragmentActivity) : FragmentStateAdapter(fa) {
        override fun getItemCount(): Int = fragmentList.size

        override fun createFragment(position: Int): Fragment = fragmentList[position]

    }
}